package com.xxpt.common.utils;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.multipart.MultipartFile;
import sun.misc.BASE64Decoder;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;
import java.net.*;
import java.nio.file.Path;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.List;

@Slf4j
public class Tools {
	private static final String REG_IMAGE = "<img(.*?)src=['\"]?(?<src>.*?)['\"]";
	/** 下划线 */
	private static final char SEPARATOR = '_';

	public static void main(String[] args) {

		// String passwd = Tools.getHashPwd("mgr", "mgr"); // 密码加密
		// String str = MD5.md5("login" + DateUtil.getDays() + ",bbn_web,");
		// System.out.println(str);
		// System.out.println(passwd);
		/*for (int i = 0; i < 1000; i++) {
			System.out.println(getUniqueNo());
		}*/
		System.out.println("434321.png".substring("434321.png".lastIndexOf(".")));
		System.out.println(fieldsTolittleHump("id,  platform_id,  uid,  id_type,  id_number,  tel,  user_name,  sex,  unit,  titlef,  titles,  titlef_fid,  industry_id,  sindustry_id,  tindustry_id,  status,  create_time"));
		/*
		 * for (int i = 0; i < 100; i++) { System.out.println(getUniqueNo()); }
		 */
	}
	/**
	 * 字段转小驼峰命名法 如：id,type_name,type_id =》 id,type_name AS typeName,type_id AS typeId
	 * @param fields
	 * @return
	 */
	public static String fieldsTolittleHump(String fields){
		String[] fieldArr = fields.split(",");
		String op = "";
		String fieldStr = "";
		for (String field : fieldArr) {
			if (field.contains("_") && (!field.contains("as") || !field.contains("AS"))) {
				field = field.trim();
				String rfield =  field.contains(".") ? field.split("\\.")[1] : field;
				field = field + " AS " + littleHump(rfield);
			}

			fieldStr += op + field;
			op = ",";
		}
		return fieldStr;
	}

	/**
	 * 字节转换
	 * @param size 字节大小
	 * @return 转换后值
	 */
	public static String convertFileSize(long size) {
		long kb = 1024;
		long mb = kb * 1024;
		long gb = mb * 1024;
		if (size >= gb) {
			return String.format("%.1f GB", (float) size / gb);
		} else if (size >= mb) {
			float f = (float) size / mb;
			return String.format(f > 100 ? "%.0f MB" : "%.1f MB", f);
		} else if (size >= kb) {
			float f = (float) size / kb;
			return String.format(f > 100 ? "%.0f KB" : "%.1f KB", f);
		} else {
			return String.format("%d B", size);
		}
	}

	public static String getHostIp() {
		try {
			return InetAddress.getLocalHost().getHostAddress();
		} catch (UnknownHostException e) {
		}
		return "127.0.0.1";
	}

	public static String getHostName() {
		try {
			return InetAddress.getLocalHost().getHostName();
		} catch (UnknownHostException e) {
		}
		return "未知";
	}

	/**
	 * 文件下载 -- 用户网页端 form 表单方式下载文件
	 * @Author masl - 2019/4/26 10:09
	 * @param fileName：文件保存名字
	 * @param filePath：文件在服务器端绝对路径
	 */
	public static void downFile(HttpServletRequest request, HttpServletResponse response, String fileName, String filePath) throws Exception {
		InputStream ins = null;
		BufferedInputStream bins = null;
		OutputStream outs = null;
		BufferedOutputStream bouts = null;
		try {
			ins = new FileInputStream(new File(filePath));
		} catch (FileNotFoundException e) {
			throw new Exception(filePath + " 文件不存在！");
		}
		try {
			//fileName = new String(fileName.getBytes("gbk"), "iso8859-1");
			String agent = request.getHeader("USER-AGENT");
			if ((agent != null) && (-1 != agent.indexOf("MSIE"))) {
				String newFileName = URLEncoder.encode(fileName, "UTF-8");
				newFileName = StringUtils.replace(newFileName, "+", "%20");
				if (newFileName.length() > 150) {
					newFileName = new String(fileName.getBytes("GB2312"), "ISO8859-1");
					newFileName = StringUtils.replace(newFileName, " ", "%20");
				}
				fileName = newFileName;
			} else if ((agent != null) && (-1 != agent.indexOf("Mozilla"))) {
				fileName = new String(fileName.getBytes("UTF-8"), "ISO8859-1");
			}
			bins = new BufferedInputStream(ins);// 放到缓冲流里面
			outs = response.getOutputStream();
			// 获取文件输出IO流
			bouts = new BufferedOutputStream(outs);
			response.setCharacterEncoding("utf-8");
			response.setContentType("application/x-download");// 设置response内容的类型
			response.setHeader("Content-disposition", "attachment;filename=" + fileName); // 设置头部信息

			int bytesRead = 0;
			byte[] buffer = new byte[8192];
			// 开始向网络传输文件流
			while ((bytesRead = bins.read(buffer, 0, 8192)) != -1) {
				bouts.write(buffer, 0, bytesRead);
			}
			bouts.flush();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (ins != null)
				ins.close();
			if (bins != null)
				bins.close();
			if (outs != null)
				outs.close();
			if (bouts != null)
				bouts.close();
		}
	}

	/**
	 * 格式内容图片访问地址
	 * @param content
	 * @return
	 */
	public static String formatContentImages(String content, String imgFolder, String fileServerWebUrl) {
		if (StringUtils.isEmpty(content)) {
			return "";
		}
		List<String> srcs = RegexUtils.regMatchAll2List(REG_IMAGE, content, "src");
		for (String src : srcs) {
			if (!src.startsWith(imgFolder) || org.apache.commons.lang.StringUtils.contains(src, "http:")) {
				continue;
			}
			content = StringUtils.replace(content, src, fileServerWebUrl + src);//替换成新路径
		}
		content = content.replaceAll("\"", "'");
		return content;
	}

	/**
	 * 保存图片文件，直接以multipartFile形式
	 * @param file
	 * @param saveFolder 文件保存文件夹绝对路径
	 * @return 返回文件名
	 * @throws IOException
	 */
	public static String saveImg(MultipartFile file, String saveFolder) throws IOException {
		return saveImg(file, saveFolder, false);
	}

	/**
	 * 保存图片文件，直接以multipartFile形式
	 * @param file
	 * @param saveFolder 文件保存文件夹绝对路径
	 * @param saveSmallImage 是否生成缩略图
	 * @return 返回文件名
	 * @throws IOException
	 */
	public static String saveImg(MultipartFile file, String saveFolder, boolean saveSmallImage) throws IOException {
		return saveImg(file, saveFolder, saveSmallImage, 300);
	}

	/**
	 * 生成文件临时目录 返回格式：tmp/432ewrew
	 * @return
	 */
	public static String getFileTmpFolder() {
		return "tmp/" + Tools.get8UUID();
	}

	/**
	 * 保存图片文件，直接以multipartFile形式
	 * @param file
	 * @param saveFolder 文件保存文件夹绝对路径
	 * @param saveSmallImage 是否生成缩略图
	 * @param smallWidth 缩略图宽度
	 * @return 返回文件名
	 * @throws IOException
	 */
	public static String saveImg(MultipartFile file, String saveFolder, boolean saveSmallImage, int smallWidth) throws IOException {
		File folder = new File(saveFolder);
		if (!folder.exists()) {
			folder.mkdirs();
		}
		FileInputStream fileInputStream = (FileInputStream) file.getInputStream();
		String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));

		String fileName = Tools.get8UUID() + suffix;
		BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(saveFolder + File.separator + fileName));
		byte[] bs = new byte[1024];
		int len;
		while ((len = fileInputStream.read(bs)) != -1) {
			bos.write(bs, 0, len);
		}
		bos.flush();
		bos.close();

		//图片压缩
		if (saveSmallImage) {
			//OperateImage.tosmallerpic(saveFolder, new File(saveFolder + fileName), "_small", fileName, smallWidth, 0, (float) 0.9);
		}
		return fileName;
	}

	/**
	 * 保存文件，直接以multipartFile形式
	 * @param file
	 * @param path 文件保存绝对路径
	 * @return 返回文件名
	 * @throws IOException
	 */
	public static String saveFile(MultipartFile file, String path) throws IOException {
		File folder = new File(path);
		if (!folder.exists()) {
			folder.mkdirs();
		}
		FileInputStream fileInputStream = (FileInputStream) file.getInputStream();
		String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));

		String fileName = Tools.get8UUID() + suffix;
		BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(path + File.separator + fileName));
		byte[] bs = new byte[1024];
		int len;
		while ((len = fileInputStream.read(bs)) != -1) {
			bos.write(bs, 0, len);
		}
		bos.flush();
		bos.close();
		return fileName;
	}

	/**
	 * 清除 html 标签
	 * @param html
	 * @return
	 */
	public static String clearHtml(String html) {
		if (html == null)
			return "";
		return html.replaceAll("</?[^><]*>", "");// 保留br标签和p标签
	}

	/*
	 * 获取 UTF-8 格式的字符串 Add mashanlin 2015-07-03
	 */
	public static String getUtf8(String msg) throws UnsupportedEncodingException {
		return new String(msg.getBytes("utf-8"), "utf-8");
	}
	/**
	 * 获取字符串的长度，如果有中文，则每个中文字符计为2位
	 * @param value 指定的字符串
	 * @return 字符串的长度
	 */
	public static int getLen(String value) {
		if (value == null || value.length() == 0) {
			return 0;
		}
		int valueLength = 0;
		String chinese = "[\u0391-\uFFE5]";
		/* 获取字段值的长度，如果含中文字符，则每个中文字符长度为2，否则为1 */
		for (int i = 0; i < value.length(); i++) {
			/* 获取一个字符 */
			String temp = value.substring(i, i + 1);
			/* 判断是否为中文字符 */
			if (temp.matches(chinese)) {
				/* 中文字符长度为2 */
				valueLength += 2;
			} else {
				/* 其他字符长度为1 */
				valueLength += 1;
			}
		}
		return valueLength;
	}

	/**
	 * @Title: Wrap
	 * @Description: 第 len 个字符换行显示
	 * @param @param str ：要换行显示的字符串
	 * @param @param len : 长度
	 * @param @param wrapFeeds ： 换行符号（如：<br/> 、 \n）
	 * @param @return
	 * @return String
	 * @throws
	 */
	public static String wrap(String str, int len, String wrapFeeds) {
		if (str == null) {
			return "";
		}
		String chinese = "[\u0391-\uFFE5]";
		int valueLength = 0;
		StringBuilder newStr = new StringBuilder();
		/* 获取字段值的长度，如果含中文字符，则每个中文字符长度为2，否则为1 */
		for (int i = 0; i < str.length(); i++) {
			/* 获取一个字符 */
			String temp = str.substring(i, i + 1);
			/* 判断是否为中文字符 */
			if (temp.matches(chinese)) {
				/* 中文字符长度为2 */
				valueLength += 2;
			} else {
				/* 其他字符长度为1 */
				valueLength += 1;
			}
			newStr.append(temp);
			if (valueLength >= len) {
				valueLength = 0;
				newStr.append("<br/>");
			}
		}
		return newStr.toString();
	}

	/**
	 * @Title: isConnection
	 * @Description: url 连通性测试
	 * @throws
	 */
	public static boolean isConnection(String url) {
		boolean flag = false;
		int counts = 0;
		if (null == url || url.length() <= 0) {
			return flag;
		}
		try {
			while (counts < 10) {
				try {
					HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
					int state = connection.getResponseCode();
					if (state == 200) {
						flag = true;
					}
					break;
				} catch (Exception e) {
					counts++;
					continue;
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return flag;
	}
	/**
	 * @Title: base64ToImg
	 * @Description: base64字符串转化成图片
	 */
	public static String base64ToImg(String imgBase64Str, String path) { //对字节数组字符串进行Base64解码并生成图片
		if (imgBase64Str == null) //图像数据为空
			return "";
		BASE64Decoder decoder = new BASE64Decoder();
		try {
			//Base64解码
			byte[] b = decoder.decodeBuffer(imgBase64Str);
			for (int i = 0; i < b.length; ++i) {
				if (b[i] < 0) {//调整异常数据
					b[i] += 256;
				}
			}
			//重构上传图片的名称
			SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
			String newImgName = df.format(new Date()) + "_" + new Random().nextInt(1000) + ".jpg";
			//生成jpeg图片
			String imgFilePath = path + newImgName;//"d://222.jpg";//新生成的图片
			OutputStream out = new FileOutputStream(imgFilePath);
			out.write(b);
			out.flush();
			out.close();
			return newImgName;
		} catch (Exception e) {
			e.printStackTrace();
			return "";
		}
	}

	/**
	 * @描述:检测是否是图片文件
	 */
	public static boolean isImg(String path) {
		if (StringUtils.isBlank(path) || !path.contains(".")) {
			return false;
		}
		String extend = path.substring(path.lastIndexOf(".") + 1).toLowerCase();
		boolean ret = false;
		List<String> list = new ArrayList<String>();
		list.add("jpg");
		list.add("jpeg");
		list.add("bmp");
		list.add("gif");
		list.add("png");
		list.add("tif");
		for (String s : list) {
			if (s.equals(extend))
				ret = true;
		}
		if (ret) {
			try {
				Image image = ImageIO.read(new File(path));
				if (image == null) {
					return false;
				}
				image = null;
			} catch (Exception e) {
				return false;
			}
		}
		return ret;
	}

	/**
	 * 随机生成六位数验证码
	 * 
	 * @return
	 */
	public static int getRandomNum() {
		Random r = new Random();
		return r.nextInt(900000) + 100000;// (Math.random()*(999999-100000)+100000)
	}

	/**
	 * 随机生成六位的短信数验证码
	 * 
	 * @return
	 */
	public static String getSmsCode() {
		Random r = new Random();
		int num = r.nextInt(900000) + 100000;
		return String.valueOf(num);
	}

	private static final String[] chars = new String[] { "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z" };

	/**
	 * 生成 8 位的唯一编码 (存在重复的机率 大概在千万分之一)
	 * @return
	 */
	public static String get8UUID() {
		StringBuffer shortBuffer = new StringBuffer();
		String uuid = UUID.randomUUID().toString().replace("-", "");
		for (int i = 0; i < 8; i++) {
			String str = uuid.substring(i * 4, i * 4 + 4);
			int x = Integer.parseInt(str, 16);
			shortBuffer.append(chars[x % 0x3E]);
		}
		return shortBuffer.toString().toLowerCase();
	}

	/**
	 * 生成 32 位的唯一编码
	 * 
	 * @return
	 */
	public static String get32UUID() {
		String uuid = UUID.randomUUID().toString().trim().replaceAll("-", "");
		return uuid;
	}

	private static long tmpID = 0;
	private static boolean tmpIDlocked = false;

	/**
	 * 生成唯一编码 Add By mashanlin 2015-6-22
	 * 
	 * @return
	 */
	public static String getUniqueNo() {
		long ltime = 0;
		while (true) {
			if (tmpIDlocked == false) {
				tmpIDlocked = true;
				ltime = Long.valueOf(new SimpleDateFormat("yyMMddhhmmssSSS").format(new Date()).toString()) * 1000;
				if (tmpID < ltime) {
					tmpID = ltime;
				} else {
					tmpID = tmpID + 1;
					ltime = tmpID;
				}
				tmpIDlocked = false;
				return Long.toString(ltime);
			}
		}
	}

	/**
	 * 
	 * @return WebRoot目录的绝对路径
	 */
	public static String getWebRootAbsolutePath() {
		String path = null;
		String folderPath = Path.class.getProtectionDomain().getCodeSource().getLocation().getPath();
		if (folderPath.indexOf("WEB-INF") > 0) {
			path = folderPath.substring(0, folderPath.indexOf("WEB-INF/classes"));
		}
		return path;
	}

	/**
	 * 把时间根据时、分、秒转换为时间段
	 * 
	 * @param StrDate
	 */
	public static String getTimes(String StrDate) {
		String resultTimes = "";

		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		Date now;

		try {
			now = new Date();
			Date date = df.parse(StrDate);
			long times = now.getTime() - date.getTime();
			long day = times / (24 * 60 * 60 * 1000);
			long hour = (times / (60 * 60 * 1000) - day * 24);
			long min = ((times / (60 * 1000)) - day * 24 * 60 - hour * 60);
			long sec = (times / 1000 - day * 24 * 60 * 60 - hour * 60 * 60 - min * 60);

			StringBuffer sb = new StringBuffer();
			// sb.append("发表于：");
			if (hour > 0) {
				sb.append(hour + "小时前");
			} else if (min > 0) {
				sb.append(min + "分钟前");
			} else {
				sb.append(sec + "秒前");
			}

			resultTimes = sb.toString();
		} catch (ParseException e) {
			e.printStackTrace();
		}

		return resultTimes;
	}

	/**
	 * 写txt里的单行内容
	 * 
	 * @param filePath
	 *            文件路径
	 * @param content
	 *            写入的内容
	 */
	public static void addAndWriteFile(String filePath, String content) {
		try {
			OutputStreamWriter write = new OutputStreamWriter(new FileOutputStream(filePath), "utf-8");
			BufferedWriter writer = new BufferedWriter(write);
			writer.write(content);
			writer.close();

		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 写txt里的单行内容
	 * 
	 *            文件路径
	 * @param content
	 *            写入的内容
	 */
	public static void writeFile(String fileP, String content) {
		String filePath = String.valueOf(Thread.currentThread().getContextClassLoader().getResource("")) + "../../"; // 项目路径
		filePath = (filePath.trim() + fileP.trim()).substring(6).trim();
		if (filePath.indexOf(":") != 1) {
			filePath = File.separator + filePath;
		}
		try {
			OutputStreamWriter write = new OutputStreamWriter(new FileOutputStream(filePath), "utf-8");
			BufferedWriter writer = new BufferedWriter(write);
			writer.write(content);
			writer.close();

		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 读取txt里的单行内容
	 * 
	 *            文件路径
	 */
	public static String readTxtFile(String fileP) {
		try {

			String filePath = String.valueOf(Thread.currentThread().getContextClassLoader().getResource("")) + "../../"; // 项目路径
			filePath = filePath.replaceAll("file:/", "");
			filePath = filePath.replaceAll("%20", " ");
			filePath = filePath.trim() + fileP.trim();
			if (filePath.indexOf(":") != 1) {
				filePath = File.separator + filePath;
			}
			String encoding = "utf-8";
			File file = new File(filePath);
			if (file.isFile() && file.exists()) { // 判断文件是否存在
				InputStreamReader read = new InputStreamReader(new FileInputStream(file), encoding); // 考虑到编码格式
				BufferedReader bufferedReader = new BufferedReader(read);
				String lineTxt = null;
				while ((lineTxt = bufferedReader.readLine()) != null) {
					return lineTxt;
				}
				read.close();
			} else {
				System.out.println("找不到指定的文件,查看此路径是否正确:" + filePath);
			}
		} catch (Exception e) {
			System.out.println("读取文件内容出错");
		}
		return "";
	}

	/**
	 * 取身份证后 6 位
	 * @param idNumber
	 * @return
	 */
	public static String getIdnumEnd6(String idNumber) {
		if (StringUtils.isBlank(idNumber))
			return "";
		if (idNumber.length() == 15)
			return idNumber.substring(9);
		if (idNumber.length() == 18)
			return idNumber.substring(12);

		return "";
	}

	/**
	 * 获取客户端IP地址   
	 */
	public static String getIpAddr(HttpServletRequest request) {
		String ipAddress = null;
		ipAddress = request.getHeader("x-forwarded-for");
		if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
			ipAddress = request.getHeader("Proxy-Client-IP");
		}
		if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
			ipAddress = request.getHeader("WL-Proxy-Client-IP");
		}
		if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
			ipAddress = request.getRemoteAddr();
			if (ipAddress.equals("127.0.0.1") || "0:0:0:0:0:0:0:1".equals(ipAddress)) {
				InetAddress inet = null;
				try {
					inet = InetAddress.getLocalHost();
				} catch (UnknownHostException e) {
					System.out.println("IP地址获取失败." + e.getMessage());
				}
				ipAddress = inet.getHostAddress();
			}
		}
		if (ipAddress != null && ipAddress.length() > 15) {
			if (ipAddress.indexOf(",") > 0) {
				ipAddress = ipAddress.substring(0, ipAddress.indexOf(","));
			}
		}
		return ipAddress;
	}

	/**
	 * 生成验证码图片
	 * @Author masl - 2019/12/23 0023 上午 8:41
	 * @param w
	 * @param h
	 * @param output
	 * @return
	 */
	public static String drawVerifCodeImg(int w, int h, ByteArrayOutputStream output) {
		BufferedImage image = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
		Graphics g = image.getGraphics();

		/*
		 * 生成背景
		 */
		// 填充背景
		g.setColor(getRandColor(220, 250));
		g.fillRect(0, 0, w, h);
		// 加入干扰线条
		for (int i = 0; i < 8; i++) {
			g.setColor(getRandColor(40, 150));
			Random random = new Random();
			int x = random.nextInt(w);
			int y = random.nextInt(h);
			int x1 = random.nextInt(w);
			int y1 = random.nextInt(h);
			g.drawLine(x, y, x1, y1);
		}
		//-----------------------

		/*
		 * 生成字符
		 */
		String code = "";

		char[] codeSeq = {'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'J', 'K', 'M', 'N', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', '2', '3', '4', '5', '6', '7', '8', '9'};
		String[] fontTypes = {"Arial", "Arial Black", "AvantGarde Bk BT", "Calibri"};
		Random random = new Random();
		StringBuilder s = new StringBuilder();
		for (int i = 0; i < 4; i++) {
			String r = String.valueOf(codeSeq[random.nextInt(codeSeq.length)]);//random.nextInt(10));
			g.setColor(new Color(50 + random.nextInt(100), 50 + random.nextInt(100), 50 + random.nextInt(100)));
			g.setFont(new Font(fontTypes[random.nextInt(fontTypes.length)], Font.BOLD, 26));
			g.drawString(r, 15 * i + 5, 19 + random.nextInt(8));
			//			g.drawString(r, i*w/4, h-5);
			s.append(r);
		}
		code = s.toString();
		//-----------------------

		g.dispose();
		try {
			ImageIO.write(image, "JPEG", output);
		} catch (IOException e) {
			e.printStackTrace();
		}

		return code;
	}

	private static Color getRandColor(int fc, int bc) {
		int f = fc;
		int b = bc;
		Random random = new Random();
		if (f > 255) {
			f = 255;
		}
		if (b > 255) {
			b = 255;
		}
		return new Color(f + random.nextInt(b - f), f + random.nextInt(b - f), f + random.nextInt(b - f));
	}

	/**
	 * @Title: littleHump
	 * @Description: 小驼峰
	 * @author: masl 2016年8月6日上午10:42:27
	 * @param @param str
	 * @param @return
	 * @return String
	 * @throws
	 */
	public static String littleHump(String str) {
		String tmp = "";
		if (str.indexOf("_") > 0) {
			int f = 0;
			for (String item : str.split("_")) {
				if (f == 0) {
					f = 1;
					tmp += item;
					continue;
				}
				char ch[] = item.toCharArray();
				if (ch[0] >= 'a' && ch[0] <= 'z')
					ch[0] = (char) (ch[0] - 32);

				tmp += new String(ch);
			}
		} else {
			return str;
		}
		return tmp;
	}

	/**
	 * @Title: bigHump
	 * @Description: 大驼峰命名法
	 * @author: masl 2016年8月6日上午10:42:27
	 * @param @param str
	 * @param @return
	 * @return String
	 * @throws
	 */
	public static String bigHump(String str) {
		String tmp = "";
		if (str.indexOf("_") > 0) {
			for (String item : str.split("_")) {
				char ch[] = item.toCharArray();
				if (ch[0] >= 'a' && ch[0] <= 'z')
					ch[0] = (char) (ch[0] - 32);

				tmp += new String(ch);
			}
		} else {
			return str;
		}
		return tmp;
	}

	/**
	 * 驼峰命名转下划线
	 */
	public static String toUnderScoreCase(String str) {
		if (str == null) {
			return null;
		}
		StringBuilder sb = new StringBuilder();
		// 前置字符是否大写
		boolean preCharIsUpperCase = true;
		// 当前字符是否大写
		boolean curreCharIsUpperCase = true;
		// 下一字符是否大写
		boolean nexteCharIsUpperCase = true;
		for (int i = 0; i < str.length(); i++) {
			char c = str.charAt(i);
			if (i > 0) {
				preCharIsUpperCase = Character.isUpperCase(str.charAt(i - 1));
			} else {
				preCharIsUpperCase = false;
			}

			curreCharIsUpperCase = Character.isUpperCase(c);

			if (i < (str.length() - 1)) {
				nexteCharIsUpperCase = Character.isUpperCase(str.charAt(i + 1));
			}

			if (preCharIsUpperCase && curreCharIsUpperCase && !nexteCharIsUpperCase) {
				sb.append(SEPARATOR);
			} else if ((i != 0 && !preCharIsUpperCase) && curreCharIsUpperCase) {
				sb.append(SEPARATOR);
			}
			sb.append(Character.toLowerCase(c));
		}
		return sb.toString();
	}

	/**
	 * 根据url连接获取域名
	 * @param url
	 * @return 域名
	 */
	public static String getHostByUrl(String url) {
		try {
			URL u = new URL(url);
			return u.getHost();
		} catch (MalformedURLException e) {
			log.error("域名解析失败,url=" + url, e);
			return null;
		}
	}
}
